package handler

import (
	v1 "blog/api/v1"
	"blog/internal/model"
	"blog/internal/service"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

type TagHandler struct {
	*Handler
	tagService service.TagService
}

func NewTagHandler(
	handler *Handler,
	tagService service.TagService,
) *TagHandler {
	return &TagHandler{
		Handler:    handler,
		tagService: tagService,
	}
}

func (h *TagHandler) CreateTag(ctx *gin.Context) {
	var req model.Tag
	if err := ctx.ShouldBindJSON(&req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, err, nil)
		return
	}
	if err := h.tagService.CreateTag(ctx, &req); err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)
}

func (h *TagHandler) GetAllTags(ctx *gin.Context) {
	tags, err := h.tagService.GetAllTags(ctx)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, tags)
}

func (h *TagHandler) DeleteTagByID(ctx *gin.Context) {
	idStr := ctx.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, err, nil)
		return
	}
	if err := h.tagService.DeleteTagByID(ctx, uint(id)); err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)
}

func (h *TagHandler) UpdateTag(ctx *gin.Context) {
	var req v1.UpdateTagRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, err, nil)
		return
	}

	if err := h.tagService.UpdateTag(ctx, req.ID, req.Name); err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}

	v1.HandleSuccess(ctx, "标签已更新")
}
